package com.credithc.customers.manager.service.impl;

import com.credithc.baseserv.core.utils.UUIDUtils;
import com.credithc.customers.base.codes.CustomerCodes;
import com.credithc.customers.base.constants.CustomerConstants;
import com.credithc.customers.base.exception.CustomerException;
import com.credithc.customers.base.mapper.*;
import com.credithc.customers.base.po.*;
import com.credithc.customers.base.ro.EmailSendRo;
import com.credithc.customers.base.service.ICommonService;
import com.credithc.customers.manager.mapper.CustomerExtendStatisticMapper;
import com.credithc.customers.manager.mapper.CustomerStatsSourceMapper;
import com.credithc.customers.manager.po.CustomerExtendStatisticPo;
import com.credithc.customers.manager.po.CustomerStatsSourcePo;
import com.credithc.customers.manager.ro.CustomerStatsRo;
import com.credithc.customers.manager.service.ScheduleService;
import com.credithc.customers.manager.utils.StatsUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author zhukai
 * @date 2019/1/4 13:35
 */
@Service
@Slf4j
public class ScheduleServiceImpl implements ScheduleService {
    @Autowired
    private ICommonService commonService;
    @Autowired
    private CustomerStatsSourceMapper sourceMapper;
    @Autowired
    private CustomerStatsMapper statsMapper;
    @Autowired
    private CustomerAbnormalMapper abnormalMapper;
    @Autowired
    private SystemInfoMapper systemInfoMapper;
    @Autowired
    private CustomerManageStatisticMapper manageStatisticMapper;
    @Autowired
    private ProductInfoStatisticMapper productInfoStatisticMapper;
    @Autowired
    private AccountInfoStatisticMapper accountInfoStatisticMapper;
    @Autowired
    private CustomerManageInfoMapper manageInfoMapper;
    @Autowired
    private CustomerExtendStatisticMapper customerExtendstatisticMapper;
    @Autowired
    private CustUnifyLoginStatisticMapper custUnifyLoginStatisticMapper;
    @Autowired
    private CustUnifyRegisterStatisticMapper registerStatisticMapper;


    @Override
    public void statsCustomerCount(String date) {
        try {
            int currentCount = statsMapper.selectCount(new CustomerStatsPo());
            CustomerStatsRo ro = new CustomerStatsRo();
            if (currentCount == 0) {
                //第一次统计，统计所有数据
                ro.setType("init");
            } else {
                //统计当天
                ro.setType("normal");
            }
            ro.setCustomerStateDateEnd(date);
            List<CustomerStatsSourcePo> homeStatsPos = sourceMapper.statsCustomerCount(ro);
            CustomerStatsPo p;
            Timestamp timestamp = new Timestamp(System.currentTimeMillis());
            int preSum = 0;
            int personalSum = 0;
            int publicSum = 0;
            for (CustomerStatsSourcePo po : homeStatsPos) {
                int count = po.getCount();
                if ("pre".equals(po.getType())) {
                    preSum += count;
                } else if ("personal".equals(po.getType())) {
                    personalSum += count;
                }
                if ("public".equals(po.getType())) {
                    publicSum += count;
                }
                p = new CustomerStatsPo();
                BeanUtils.copyProperties(po, p);
                p.setId(UUIDUtils.getUUID());
                p.setCreateTime(timestamp);
                p.setStatsType(CustomerConstants.STATS_CUSTOMER_COUNT);
                statsMapper.insert(p);
            }
            if (preSum > 0) {
                createSum("pre", timestamp, date, preSum);
            }
            if (personalSum > 0) {
                createSum("personal", timestamp, date, personalSum);
            }
            if (publicSum > 0) {
                createSum("public", timestamp, date, publicSum);
            }
        } catch (DataAccessException e) {
            log.error("========================================定时生成报表执行失败" + e.getMessage());
            throw new CustomerException(CustomerCodes.SCHEDULE_EXECUTE_FAIL);
        }
    }

    private void createSum(String type, Timestamp timestamp, String date, int sum) {
        CustomerStatsPo p = new CustomerStatsPo();
        p.setStatsType(CustomerConstants.STATS_CUSTOMER_SUM);
        p.setType(type);
        List<CustomerStatsPo> list = statsMapper.select(p);
        if (list.size() == 0) {
            p.setId(UUIDUtils.getUUID());
            p.setCreateTime(timestamp);
            p.setDate(date);
            p.setCount(sum);
            statsMapper.insert(p);
        } else if (list.size() == 1) {
            CustomerStatsPo updatePo = list.get(0);
            updatePo.setCount(updatePo.getCount() + sum);
            statsMapper.updateByPrimaryKey(updatePo);
        }
    }

    @Override
    public void statsPreChange(String date) {
        try {
            List<CustomerStatsSourcePo> preChangePos = sourceMapper.statsCustomerChange();
            Timestamp timestamp = new Timestamp(System.currentTimeMillis());
            for (CustomerStatsSourcePo po : preChangePos) {
                int count = po.getCount();
                if ("preTotal".equals(po.getType())) {
                    createChangeSum("preTotal", timestamp, date, count);
                } else if ("preChange".equals(po.getType())) {
                    createChangeSum("preChange", timestamp, date, count);
                }
            }
        } catch (DataAccessException e) {
            log.error("========================================定时生成报表执行失败" + e.getMessage());
            throw new CustomerException(CustomerCodes.SCHEDULE_EXECUTE_FAIL);
        }
    }

    private void createChangeSum(String type, Timestamp timestamp, String date, int sum) {
        CustomerStatsPo p = new CustomerStatsPo();
        p.setStatsType(CustomerConstants.STATS_PRE_CUSTOMER_CHANGE);
        p.setType(type);
        List<CustomerStatsPo> list = statsMapper.select(p);
        if (list.size() == 0) {
            p.setId(UUIDUtils.getUUID());
            p.setCreateTime(timestamp);
            p.setDate(date);
            p.setCount(sum);
            statsMapper.insert(p);
        } else if (list.size() == 1) {
            CustomerStatsPo updatePo = list.get(0);
            updatePo.setCount(sum);
            statsMapper.updateByPrimaryKey(updatePo);
        }
    }

    @Override
    public Map<String, Object> editAbnormalAndEmail() {
        log.info("异常信息邮件通知定时任务开始--------------------------");
        Example example = new Example(CustomerAbnormalPo.class);
        example.setDistinct(false);
        Example.Criteria criteria = example.createCriteria();
        //批量处理待处理状态
        criteria.andEqualTo("status", CustomerConstants.ABNORMAL_STATUS_TODO);
        List<CustomerAbnormalPo> poList = abnormalMapper.selectByExample(example);
        for (CustomerAbnormalPo po : poList) {
            //客户信息异常
            EmailSendRo ro = new EmailSendRo();
            String emailContent;
            if (po.getAbnormalType().equals(CustomerConstants.ABNORMAL_TYPE_ERROR)) {
                emailContent = "您好,客户号:" + po.getCustomerNo() + ",姓名" + po.getCustomerName() + ",在一账通系统中已存在相同证件信息客户,已存在异常客户号为"
                        + po.getAssociatedId() + ",请联系相关人员核实该证件信息";
            } else {
                emailContent = "您好,客户号:" + po.getCustomerNo() + ",姓名" + po.getCustomerName() + ",与一账通系统对应客户证件信息不一致,一账通系统证件信息为"
                        + po.getAssociatedId() + ",请联系相关人员核实该证件信息";
            }
            SystemInfoPo systemInfoPo = new SystemInfoPo();
            systemInfoPo.setSystemSign(po.getSubSystemSign());
            List<SystemInfoPo> systemInfoPoList = systemInfoMapper.select(systemInfoPo);
            ro.setTo(systemInfoPoList.get(0).getMailReceiver());
            ro.setSubject("异常信息通知[一账通]");
            ro.setBody(emailContent);
            commonService.sendEmail(ro);
        }
        return null;

    }


    public void statsManageCount(String date) {
        try {
            int currentCount = manageStatisticMapper.selectCount(new CustomerManageStatisticPo());
            CustomerStatsRo ro = new CustomerStatsRo();
            if (currentCount == 0) {
                //第一次统计，统计所有数据
                ro.setType("init");
            } else {
                //统计当天
                ro.setType("normal");
            }
            ro.setCustomerStateDateEnd(date);
            List<CustomerStatsSourcePo> homeStatsPos = sourceMapper.statsCustomerCount(ro);
            CustomerStatsPo p;
            Timestamp timestamp = new Timestamp(System.currentTimeMillis());
            int preSum = 0;
            int personalSum = 0;
            int publicSum = 0;
            for (CustomerStatsSourcePo po : homeStatsPos) {
                int count = po.getCount();
                if ("pre".equals(po.getType())) {
                    preSum += count;
                } else if ("personal".equals(po.getType())) {
                    personalSum += count;
                }
                if ("public".equals(po.getType())) {
                    publicSum += count;
                }
                p = new CustomerStatsPo();
                BeanUtils.copyProperties(po, p);
                p.setId(UUIDUtils.getUUID());
                p.setCreateTime(timestamp);
                p.setStatsType(CustomerConstants.STATS_CUSTOMER_COUNT);
                statsMapper.insert(p);
            }
            if (preSum > 0) {
                createSum("pre", timestamp, date, preSum);
            }
            if (personalSum > 0) {
                createSum("personal", timestamp, date, personalSum);
            }
            if (publicSum > 0) {
                createSum("public", timestamp, date, publicSum);
            }
        } catch (DataAccessException e) {
            log.error("========================================定时生成报表执行失败" + e.getMessage());
            throw new CustomerException(CustomerCodes.SCHEDULE_EXECUTE_FAIL);
        }
    }


    @Override
    public void statsManageStatistic(String date) {
        try {
            CustomerManageStatisticPo po = new CustomerManageStatisticPo();
            String yesterDay = StatsUtils.getPastDate(1, date);
            po.setDate(yesterDay);
            int count = manageStatisticMapper.selectCount(po);
            if (count == 0) {
                List<CustomerManageStatisticPo> manageStatisticPos = manageStatisticMapper.getManageInit(date, yesterDay);
                manageStatisticMapper.insertList(manageStatisticPos);
            }
        } catch (DataAccessException e) {
            log.error("========================================客户各业务系统统计失败" + date + ":" + e.getMessage());
        }

    }

    @Override
    public void statsCustomerExtend(LocalDate currentDate) {
        CustomerExtendStatisticPo po = new CustomerExtendStatisticPo();
        LocalDate date = currentDate.minusDays(1);
        po.setDate(date);
        log.info("po="+po+";date="+date+";currentDate="+currentDate);
        int count = customerExtendstatisticMapper.selectCount(po);
        if (count == 0) {
            List<CustomerExtendStatisticPo> polist = customerExtendstatisticMapper.getListGroupBySubSystemSign(date, currentDate);
            customerExtendstatisticMapper.insertList(polist);
        }
    }

    @Override
    public void statsProductInfo(String currentDay) {
        try {
            ProductInfoStatisticPo po = new ProductInfoStatisticPo();
            String yesterDay = StatsUtils.getPastDate(1, currentDay);
            po.setDate(yesterDay);
            int count = productInfoStatisticMapper.selectCount(po);
            List<ProductInfoStatisticPo> productInfoStatisticPos = productInfoStatisticMapper.getProductInit(currentDay, yesterDay);
            if (count > 0) {
                productInfoStatisticMapper.delete(po);
            }
            productInfoStatisticMapper.insertList(productInfoStatisticPos);
            //统计各个维度时间为空的数据量
            List<ProductInfoStatisticPo> productInfoStatisticPosTimeNull = productInfoStatisticMapper.getProductInitTimeNull();
            //删除数据
            ProductInfoStatisticPo poTimeNull = new ProductInfoStatisticPo();
            poTimeNull.setDate("0000-00-00");
            productInfoStatisticMapper.delete(poTimeNull);
            //插入数据
            productInfoStatisticMapper.insertList(productInfoStatisticPosTimeNull);
        } catch (DataAccessException e) {
            e.printStackTrace();
            log.error("========================================客户持有产品记录系统统计失败" + currentDay + ":" + e.getMessage());
        }
    }

    @Override
    public void statsAccountInfo(String currentDay) {
        try {
            AccountInfoStatisticPo po = new AccountInfoStatisticPo();
            String yesterDay = StatsUtils.getPastDate(1, currentDay);
            po.setDate(yesterDay);
            int count = accountInfoStatisticMapper.selectCount(po);
            List<AccountInfoStatisticPo> accountInfoStatisticPos = accountInfoStatisticMapper.getAccountInit(currentDay, yesterDay);
            if (count > 0) {
                accountInfoStatisticMapper.delete(po);
            }
            accountInfoStatisticMapper.insertList(accountInfoStatisticPos);
            //统计各个维度时间为空的数据量
            List<AccountInfoStatisticPo> accountInfoStatisticPosTimeNull = accountInfoStatisticMapper.getProductInitTimeNull();
            //删除数据
            AccountInfoStatisticPo poTimeNull = new AccountInfoStatisticPo();
            poTimeNull.setDate("0000-00-00");
            accountInfoStatisticMapper.delete(poTimeNull);
            //插入数据
            accountInfoStatisticMapper.insertList(accountInfoStatisticPosTimeNull);

        } catch (DataAccessException e) {
            log.error("========================================客户信息记录系统统计失败" + currentDay + ":" + e.getMessage());
        }
    }

    @Override
    public void statsProductInfoSystem(String doDate, String system) {
        try {
            ProductInfoStatisticPo po = new ProductInfoStatisticPo();
            String yesterDay = StatsUtils.getPastDate(1, doDate);
            po.setDate(yesterDay);
            po.setProductSourceSystem(system);
            int count = productInfoStatisticMapper.selectCount(po);
            List<ProductInfoStatisticPo> productInfoStatisticPos = productInfoStatisticMapper.getProductInitBySys(doDate, yesterDay, system);
            if (count > 0) {
                productInfoStatisticMapper.delete(po);
            }
            productInfoStatisticMapper.insertList(productInfoStatisticPos);
        } catch (DataAccessException e) {
            e.printStackTrace();
            log.error("========================================客户持有产品记录系统统计失败" + doDate + ":" + e.getMessage());
        }
    }

    @Override
    public void statsAccountInfoSystem(String doDate, String system) {
        try {
            AccountInfoStatisticPo po = new AccountInfoStatisticPo();
            String yesterDay = StatsUtils.getPastDate(1, doDate);
            po.setDate(yesterDay);
            po.setSubSystemSign(system);
            int count = accountInfoStatisticMapper.selectCount(po);
            List<AccountInfoStatisticPo> accountInfoStatisticPos = accountInfoStatisticMapper.getAccountInitSys(doDate, yesterDay, system);
            if (count > 0) {
                accountInfoStatisticMapper.delete(po);
            }
            accountInfoStatisticMapper.insertList(accountInfoStatisticPos);
        } catch (DataAccessException e) {
            log.error("========================================客户信息记录系统统计失败" + doDate + ":" + e.getMessage());
        }
    }

    @Override
    public void statsProductInfoDate(String currentDay) {
        try {
            ProductInfoStatisticPo po = new ProductInfoStatisticPo();
            String yesterDay = StatsUtils.getPastDate(1, currentDay);
            po.setDate(yesterDay);
            int count = productInfoStatisticMapper.selectCount(po);
            List<ProductInfoStatisticPo> productInfoStatisticPos = productInfoStatisticMapper.getProductInit(currentDay, yesterDay);
            if (count > 0) {
                productInfoStatisticMapper.delete(po);
            }
            productInfoStatisticMapper.insertList(productInfoStatisticPos);
        } catch (DataAccessException e) {
            e.printStackTrace();
            log.error("========================================客户持有产品记录系统统计失败" + currentDay + ":" + e.getMessage());
        }
    }

    @Override
    public void statsAccountInfoDate(String currentDay) {
        try {
            AccountInfoStatisticPo po = new AccountInfoStatisticPo();
            String yesterDay = StatsUtils.getPastDate(1, currentDay);
            po.setDate(yesterDay);
            int count = accountInfoStatisticMapper.selectCount(po);
            List<AccountInfoStatisticPo> accountInfoStatisticPos = accountInfoStatisticMapper.getAccountInit(currentDay, yesterDay);
            if (count > 0) {
                accountInfoStatisticMapper.delete(po);
            }
            accountInfoStatisticMapper.insertList(accountInfoStatisticPos);
        } catch (DataAccessException e) {
            log.error("========================================客户信息记录系统统计失败" + currentDay + ":" + e.getMessage());
        }
    }

    @Override
    public void statsLoginFlow(String currentDay) {
        try {
            CustUnifyLoginStatisticPo po = new CustUnifyLoginStatisticPo();
            String yesterDay = StatsUtils.getPastDate(1, currentDay);
            po.setDate(yesterDay);
            int count = custUnifyLoginStatisticMapper.selectCount(po);
            List<CustUnifyLoginStatisticPo> custUnifyLoginStatisticPos = custUnifyLoginStatisticMapper.getLoginFlowInit(currentDay, yesterDay);
            //List<CustUnifyLoginStatisticPo> custUnifyLoginStatisticPos1 = custUnifyLoginStatisticMapper.getLoginFlowAll(currentDay, yesterDay);
            if (count > 0) {
                custUnifyLoginStatisticMapper.delete(po);
            }
            //custUnifyLoginStatisticPos.addAll(custUnifyLoginStatisticPos1);
            custUnifyLoginStatisticMapper.insertList(custUnifyLoginStatisticPos);
        } catch (DataAccessException e) {
            e.printStackTrace();
            log.error("========================================用户各系统统一登陆统计异常" + currentDay + ":" + e.getMessage());
        }
    }

    @Override
    public void statsRegister(String currentDayTime) {
        try {
            CustUnifyRegisterStatisticPo po = new CustUnifyRegisterStatisticPo();
            String yesterDayTime = StatsUtils.getPastDateTime(1);
            String today = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            po.setDate(today);
            po.setType(0);
            log.info("=====================统计各系统当日(按小时)注册数入参：today=" + currentDayTime + "    yesterDayTime=" + yesterDayTime);
            int count = registerStatisticMapper.selectCount(po);
            List<CustUnifyRegisterStatisticPo> registerStatisticPos = registerStatisticMapper.statisticRegister(currentDayTime, yesterDayTime);
            if (count > 0) {
                registerStatisticMapper.delete(po);
            }
            registerStatisticMapper.insertList(registerStatisticPos);
            //删除冗余注册数+授权注册数+授权登录数均为0字段
            CustUnifyRegisterStatisticPo po1 = new CustUnifyRegisterStatisticPo();
            po1.setDate(today);
            po1.setType(0);
            po1.setRegisterNum(0);
            po1.setAuthRegisterNum(0);
            po1.setAuthLoginNum(0);
            registerStatisticMapper.delete(po1);
        } catch (DataAccessException e) {
            log.error("========================================统计各系统当日(按小时)注册数异常" + currentDayTime + ":" + e.getMessage());
        }
    }

    @Override
    public void statsRegisterSum(String currentDayTime) {
        try {
            CustUnifyRegisterStatisticPo po = new CustUnifyRegisterStatisticPo();
            String yesterDayTime = StatsUtils.getPastDateTime(1);
            String today = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            String yesterDay = StatsUtils.getPastDate(1, today);
            po.setDate(today);
            po.setType(1);
            log.info("=====================统计各系统累计注册(按天)总数入参：currentDayTime=" + currentDayTime + "    yesterDayTime=" + yesterDayTime + "     yesterDay=" + yesterDay);
            int count = registerStatisticMapper.selectCount(po);
            List<CustUnifyRegisterStatisticPo> registerStatisticPos = registerStatisticMapper.statisticRegisterSum(currentDayTime, yesterDayTime, yesterDay, today);
            if (count > 0) {
                registerStatisticMapper.delete(po);
            }
            registerStatisticMapper.insertList(registerStatisticPos);
        } catch (DataAccessException e) {
            log.error("========================================统计各系统累计注册(按天)总数异常" + currentDayTime + ":" + e.getMessage());
        }
    }

}
